package cop;

import java.awt.Graphics2D;

import resources.ResMgr;
import resources.Sprite;
import utils.MyException;

import engine.Actor;
import engine.Room;

public class Cannon extends Actor {

	private Sprite base;
	private int timer;
	private int targetAngle;
	public static int DELAY = 30;

	public Cannon() {
		setSpr("cannon");
		timer = (int) (Math.random() * DELAY);
		setSprAngle(90);
		targetAngle = 90;
		setDepth(10);
		try {
			base = (Sprite) ResMgr.get().get("cannonBase");
		} catch (MyException e) {}
	}

	@Override
	public void paint(Graphics2D g) {
		super.paint(g);
		base.paint(g, getXPos(), getYPos(), (int) getSprIndex(), getSprIndexOOBB(), getSprXScale(), getSprYScale(), 0);
	}

	@Override
	public void step(Room room, float fpsFactor) {
		super.step(room, fpsFactor);
		// step
		float d = (targetAngle - getSprAngle() - 180) % 360 + 180;
		setSprAngle(getSprAngle() + Math.signum(d));
		// timer
		if (Math.abs(getSprAngle() - targetAngle) <= 1 && ++timer >= DELAY) {
			timer = 0;
			randomize(room);
			shoot(room);
		}
	}

	private void shoot(Room room) {
		Bullet b = new Bullet();
		b.setSpd(-20 * (float) Math.sin(getSprAngle() * Math.PI / 180), getSprAngle());
		room.addActor(b, getXPos(), getYPos());
	}

	private void randomize(Room room) {
		targetAngle = (int) (((getXPos() > room.getSize().getWidth() / 2) ? -1 : 1) * (Math.random() * 20 + Math.random() * 20 + 1) + 90);
	}
}
